package com.nus.servlets;

import com.nus.beans.User;
import com.nus.beans.UserStatus;
import com.nus.database.UserDBManager;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;

/**
 * Created by IntelliJ IDEA.
 * User: dell
 * Date: 9/24/12
 * Time: 8:19 PM
 * To change this template use File | Settings | File Templates.
 */
public class DeleteUserServlet extends AbstractServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String userIdParam = request.getParameter("users");
        int userId = Integer.parseInt(userIdParam);

        Connection connection = getUserDatabaseConnection(request);
        UserDBManager userDBManager = new UserDBManager(connection);

        String errorMessage = "";
        User user = userDBManager.getUser(userId);
        User currentUser = (User) request.getSession().getAttribute("user");
        if(currentUser.getUserId() == userId){
            errorMessage = "You can't delete your own user account.";
        } else if (userDBManager.isActiveProjectsAvailable(userId)) {
            errorMessage = "User has active projects. Delete request has rejected.";

        } else if(user.getStatus().equals(UserStatus.DELETED)){
            errorMessage = "User has already been deleted. Delete request has rejected.";
        } else {
            userDBManager.deleteUser(user);
            errorMessage = "User successfully deleted";
        }

        userDBManager.close();

        request.setAttribute("ERROR_MESSAGE", errorMessage);

        RequestDispatcher requestDispatcher = request.getRequestDispatcher("viewUsers.do");
        requestDispatcher.forward(request, response);
    }
}
